package com.fjnu.controller;

import com.fjnu.domain.entity.Category;
import com.fjnu.domain.vo.ResponseResult;
import com.fjnu.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/blog-api/v0.1/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/delete")
    public ResponseResult<String> delete(@RequestParam String categoryId) {
        int result = categoryService.deleteCategory(Integer.parseInt(categoryId));
        if (result > 0) {
            return ResponseResult.success("分类删除成功");
        }
        return ResponseResult.error("分类删除失败");
    }

    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody Category category) {
        int result = categoryService.addCategory(category);
        if (result > 0) {
            return ResponseResult.success("分类添加成功");
        }
        return ResponseResult.error("分类添加失败");
    }

    @GetMapping("/list")
    public ResponseResult<List<Category>> list() {
        List<Category> categories = categoryService.getAllCategories();

        if (categories == null) {
            throw new RuntimeException("分类服务返回空结果");
        }

        if (categories.isEmpty()) {
            return ResponseResult.success("查询成功，但未找到分类数据", Collections.emptyList());
        }

        return ResponseResult.success(categories);
    }
}